import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { JwtService } from '@nestjs/jwt'
import { Inject } from '@nestjs/common/decorators';

@Controller('/user')
export class UserController {
  constructor(private readonly userService: UserService) { }
  @Inject(JwtService)
  private JwtService: JwtService

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.userService.create(createUserDto);
  }

  @Post('/login')
  async login(@Body() createUserDto: CreateUserDto) {
    const founduser = await this.userService.login(createUserDto)
    const accesstoken = this.JwtService.sign({
      user: {
        username: founduser.username,
        sub: founduser.id,
        password: founduser.password,
        nickname: founduser.nickname,
        avatar: founduser.avatar,
      }
    })
    if (founduser) {
      return {
        // username: founduser.username,
        // password: founduser.password,
        ...founduser,
        access_token: `Bearer ${accesstoken}`
      }
    }
    return this.userService.login(createUserDto);
  }

  @Get('/login')
  findAll() {
    return this.userService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.userService.findOne(+id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.userService.update(+id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.userService.remove(+id);
  }
}
